package com.zzu.base.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {
    // 队列名称
    public static final String DIRECT_QUEUE = "direct.queue";
    public static final String DIRECT_EXCHANGE = "direct.exchange";
    public static final String DIRECT_ROUTING_KEY = "direct.routing.key";
    @Value("${spring.rabbitmq.queue.durable}")
    public boolean queueDurable;
    @Value("${spring.rabbitmq.queue.exclusive}")
    public boolean queueExclusive;
    @Value("${spring.rabbitmq.queue.autoDelete}")
    public boolean queueAutoDelete;
    @Value("${spring.rabbitmq.exchange.durable}")
    public boolean exchangeDurable;
    @Value("${spring.rabbitmq.exchange.autoDelete}")
    public boolean exchangeAutoDelete;
    // 配置 Jackson 消息转换器
    @Bean
    public MessageConverter messageConverter() {
        // 使用 Jackson 序列化消息体
        return new Jackson2JsonMessageConverter();
    }
    @Bean
    public Queue rabbitmqDemoDirectQueue() {
        /**
         * 1、name:    队列名称
         * 2、durable: 是否持久化
         * 3、exclusive: 是否独享、排外的。如果设置为true，定义为排他队列。则只有创建者可以使用此队列。也就是private私有的。
         * 4、autoDelete: 是否自动删除。也就是临时队列。当最后一个消费者断开连接后，会自动删除。
         * */
        return new Queue(DIRECT_QUEUE, queueDurable, queueExclusive, queueAutoDelete);
    }

    @Bean
    public DirectExchange rabbitmqDemoDirectExchange() {
        //Direct交换机
        return new DirectExchange(DIRECT_EXCHANGE, exchangeDurable, exchangeAutoDelete);
    }

    @Bean
    public Binding bindDirect() {
        //链式写法，绑定交换机和队列，并设置匹配键
        return BindingBuilder
                //绑定队列
                .bind(rabbitmqDemoDirectQueue())
                //到交换机
                .to(rabbitmqDemoDirectExchange())
                //并设置匹配键
                .with(DIRECT_ROUTING_KEY);
    }
}
